package com.dsr.service.impl;

import cn.hutool.core.date.DateTime;
import com.dsr.consts.PageResult;
import com.dsr.consts.Result;
import com.dsr.consts.e.BaseProperty;
import com.dsr.consts.e.UserProperty;
import com.dsr.controller.UserController;
import com.dsr.dao.UserDao;
import com.dsr.entity.User;
import com.dsr.service.UserService;
import com.dsr.util.BasicUtil;
import com.dsr.util.IdWorker;
import com.dsr.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.BagUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author dsr
 * @since 2020-08-27
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public Result getEntity(String id) {
        User entity = userDao.selectByPrimaryKey(id);
        return Result.success(entity);
    }

    @Override
    public Result save(User user) {
        userDao.insertSelective(user);
        return Result.success("保存成功");
    }

    @Override
    public Result update(User user) {
        userDao.updateByPrimaryKeySelective(user);
        return Result.success("修改成功");

    }

    @Override
    public Result delete(String id) {
        if (StringUtils.isNotEmpty(id)) {
            List<String> ids = Arrays.asList(id.split(","));
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", ids);
            userDao.deleteByExample(example);
            return Result.success("删除成功");
        }
        return Result.error("请选择要删除的行");
    }

    @Override
    public Result query(int page, int size, User user) {
        PageHelper.startPage(page, size);
        List<User> entityList = userDao.select(user);
        PageInfo<User> pageInfo = new PageInfo<>(entityList);
        return Result.success(new PageResult<User>(pageInfo.getTotal(), pageInfo.getList()));
    }

    @Override
    public Result list() {
        return Result.success(userDao.selectAll());
    }

    @Override
    public Result login(User user) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx49dc4b7656c0d88e&secret=37e0ea32a9d25f1cb49f6211f628c7b6&js_code=" + user.getCode() + "&grant_type=authorization_code";
        String getText = restTemplate.getForObject(url, String.class);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, String> map = objectMapper.readValue(getText, HashMap.class);
            user.setOpenId(map.get(UserProperty.OPEN_ID));
            user.setDel(0);
            User userCheck = new User();
            userCheck.setOpenId(map.get(UserProperty.OPEN_ID));
            userCheck = userDao.selectOne(userCheck);
            if (userCheck != null) {
                user = userCheck;
            }
            if(user.getDel()==1){
                return Result.error("你已经被封禁,请联系管理员");
            }
            user.setSessionKey(map.get(UserProperty.SESSION_KEY));
            user.setLoginDate(DateTime.now());
            if (StringUtils.isNotEmpty(user.getId())) {
                userDao.updateByPrimaryKeySelective(user);
            } else {
                user.setId(String.valueOf(idWorker.nextId()));
                userDao.insertSelective(user);
            }
            map.put(UserProperty.USER_ID, user.getId());
            map.put(UserProperty.NICK_NAME, user.getNickName());
            map.put(UserProperty.AVATAR_URl, user.getAvatarUrl());
            map.put(BaseProperty.ROLE,UserProperty.USER);
            BasicUtil.setCookie("token", JwtUtil.getToken(map));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(user);
    }

    @Override
    public Result checkLogin(String id) {
        User user = userDao.selectByPrimaryKey(id);
        user.setLoginDate(DateTime.now());
        Map<String, String> map = new HashMap<String, String>();
        map.put(UserProperty.USER_ID, user.getId());
        map.put(UserProperty.NICK_NAME, user.getNickName());
        map.put(UserProperty.AVATAR_URl, user.getAvatarUrl());
        map.put(UserProperty.SESSION_KEY, user.getSessionKey());
        map.put(UserProperty.OPEN_ID, user.getOpenId());
        map.put(BaseProperty.ROLE,UserProperty.USER);
        BasicUtil.setCookie("token", JwtUtil.getToken(map));
        userDao.updateByPrimaryKeySelective(user);
        return Result.success("登录成功");
    }
}